<template>
	<z-paging-swiper class="page">
		<CustomNavBar title="优派">
			<template v-slot:left v-if="showHeader">
				<view class="back uni-flex uni-align-center uni-justify-center" @click="goBack"><uni-icons type="left"
						size="20"></uni-icons></view>
			</template>
		</CustomNavBar>
		<city-head></city-head>
		<z-tabs ref="tabs1" v-if="tabsList.length > 0" :list="tabsList" :current="current" @change="changeTab"
			scroll-count="0" :active-style="{fontWeight: '600',fontSize: '36rpx',color: '#333333'}"
			:inactive-style="{fontWeight: '400',fontSize: '28rpx',color: '#666666'}">
			<template slot="right">
				<view class="selectMore uni-flex uni-justify-between uni-align-center" @click="openSelectService">
					<!-- 筛选 -->
					<uni-icons type="search" size="28" color="#999999"></uni-icons>
				</view>
			</template>
		</z-tabs>

		<!-- 空状态：当tabsList为空且初始化完成时显示 -->
		<view v-if="tabsList.length === 0 && initialized" class="empty-state">
			<text class="empty-text">此区域暂无服务类目</text>
		</view>

		<!-- swiper必须设置height:100%，因为swiper有默认的高度，只有设置高度100%才可以铺满页面  -->
		<swiper class="swiper" :current="current" @change="onChange">
			<swiper-item class="swiper-item" v-for="(item, index) in tabsList" :key="index">
				<view-sonic-item ref="listItem" :tabIndex="index" :currentIndex="current"
					:serviceTabs="item.children" :item-idsStr="itemIdsArr"></view-sonic-item>
			</swiper-item>
		</swiper>
		<view class="fab_btn uni-flex uni-align-center uni-justify-center" @click="jumpToCart">
			<uni-icons type="cart-filled" size="25" color="#2F80ED"></uni-icons>
		</view>
	</z-paging-swiper>
</template>

<script setup>
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		ref,
		reactive,
		toRefs,
		onMounted,
		onUnmounted
	} from 'vue';
	import CustomNavBar from "@/components/custom-navbar/index.vue";
	import viewSonicItem from './viewSonicItem.vue';
	import cityHead from "@/components/city-head/index.vue";
	import {
		getServiceByArea,
	} from "@/api/home.js";
	import {
		getAreaid
	} from "@/common/util.js";

	const tabsList = ref([]); // 现在作为一级类目（原serviceList）
	const current = ref(0);
	const tabs = ref([]); // 可保留用于存储原始二级类目数据
	const initialized = ref(false); // 标记接口初始化完成
	const state = reactive({
		showHeader: false,
	});
	const {
		showHeader
	} = toRefs(state);

	// 页面加载时判断是否显示返回按钮
	onLoad((query) => {
		console.log(query.from, 'query');
		showHeader.value = query.from === 'home';
	
	});

	// 切换标签页
	const changeTab = (index) => {
		current.value = index;
	};

	// 监听swiper切换
	const onChange = (e) => {
		current.value = e.detail.current;
	};

	// 刷新当前标签页列表
	const reloadCurrentList = () => {
		listItem.value[current.value]?.reload();
	};

	// 打开服务筛选页
	const openSelectService = () => {
		uni.navigateTo({
			url: "/pages/tabBars/selectService/selectService?eventName=categorySelected"
		});
	};

	// 返回上一页
	const goBack = () => {
		uni.navigateBack({
			delta: 1
		});
	};

	// 跳转到购物车
	const jumpToCart = () => {
		uni.navigateTo({
			url: "/pages/shoppingCart/cart"
		});
	};

	// 拆分groupList中的id，提取serviceId和groupId
	const splitGroupId = (groupId) => {
		const parts = groupId.split('-');
		return {
			serviceId: parts[0], // 提取'-'符号前面的值
			groupId: parts[1] // 提取'-'符号后面的值
		};
	};

	// 获取服务列表数据（核心修改：互换一级/二级类目）
	const ApigetServiceByArea = async (areaId) => {
		const requestAreaId = areaId || getAreaid();
		tabsList.value = [];
		tabs.value = [];
		initialized.value = false;

		try {
			const res = await getServiceByArea({
				areaId: requestAreaId
			});

			if (res.code !== 200) {
				throw new Error(`接口请求失败：${res.msg || '未知错误'}`);
			}

			// 处理数据：互换一级/二级类目
			const data = res.data || {};
			// 1. 将原serviceList作为一级类目（tabs标签）
			const firstLevelList = data.serviceList || [];
			// 2. 将原groupList作为二级类目（标签对应的子内容）
			const secondLevelList = data.groupList || [];

			// 3. 构建二级类目映射表（按一级类目ID分组）
			const secondLevelMap = {};
			secondLevelList.forEach(group => {
				// 拆分group.id获取serviceId
				const {
					serviceId
				} = splitGroupId(group.id);
				if (!secondLevelMap[serviceId]) {
					secondLevelMap[serviceId] = [];
				}
				secondLevelMap[serviceId].push(group);
			});

			// 4. 为一级类目添加二级子类目
			tabsList.value = firstLevelList.map(firstLevel => ({
				...firstLevel,
				// 每个一级类目对应的二级类目列表
				children: secondLevelMap[firstLevel.id] || []
			}));

			tabs.value = secondLevelList; // 存储原始二级类目数据备用
			initialized.value = true;

		} catch (err) {
			console.error('获取服务列表失败:', err.message || err);
			uni.showToast({
				title: '此区域暂无服务数据',
				icon: 'none',
				duration: 3000
			});
			// 错误时重置状态
			tabsList.value = [];
			tabs.value = [];
			initialized.value = true;
		}
	};

	// 页面挂载时初始化数据
	onMounted(() => {
		ApigetServiceByArea();
		// 绑定地区选择事件监听
		uni.$off('areaSelected', handleAreaSelected);
		uni.$on('areaSelected', handleAreaSelected);
	});

	// 地区切换事件处理
	const handleAreaSelected = (data) => {
		if (data?.areaId) {
			ApigetServiceByArea(data.areaId);
		}
	};

	// 页面卸载时移除事件监听
	onUnmounted(() => {
		uni.$off('areaSelected', handleAreaSelected);
	});
</script>

<style lang="scss" scoped>
	.page {
		position: relative;

		.back {
			width: 44rpx;
			height: 44rpx;
			background: rgba(255, 255, 255, 0.6);
			border-radius: 50%;
		}

		.swiper {
			height: 100%;
		}

		.selectMore {
			width: 80rpx;
			font-weight: 500;
			font-size: 28rpx;
			color: #666666;
			padding: 0 25rpx;

			.more_img {
				width: 16rpx;
				height: 16rpx;
				margin-top: 6rpx;
			}
		}

		.fab_btn {
			position: fixed;
			right: 42rpx;
			bottom: 166rpx;
			width: 100rpx;
			height: 100rpx;
			border-radius: 50%;
			background: #FFFFFF;
			box-shadow: 0rpx 7rpx 17rpx 0rpx #DFE1E4;
		}
	}

	// 空状态样式
	.empty-state {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 70%;

		.empty-text {
			font-size: 30rpx;
			color: #999999;
			text-align: center;
		}
	}
</style>